package pay.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.wxapi.MyWxApi;
import com.example.xuegengwang.xuegengwang.wxapi.WXEntryActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.Map;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import utils.MyLogUtils;
import utils.ToastUtils;
import view.EncashDialog;
import view.WaitingDialog;

/**
 * Created by Administrator on 2017/4/25.
 * 我的余额，提现页
 */
@ContentView(R.layout.encash)
public class EnCash extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.common_back)
    private ImageView common_back;
    @ViewInject(R.id.encash_money)
    private TextView encash_money;
    @ViewInject(R.id.encash_history)
    private TextView encash_history;
    @ViewInject(R.id.encash_weixin_layout)
    private RelativeLayout encash_weixin_layout;
    @ViewInject(R.id.encash_zhifubao_layout)
    private RelativeLayout encash_zhifubao_layout;
    @ViewInject(R.id.encash_weixin)
    private ImageView encash_weixin;
    @ViewInject(R.id.encash_zhifubao)
    private ImageView encash_zhifubao;
    @ViewInject(R.id.encash_price)
    private TextView encash_price;
    @ViewInject(R.id.encash_commit)
    private TextView encash_commit;

    private String type;
    private String money;
    private final int SDK_PAY_FLAG = 1;
    private EncashDialog encashDialog;
    private Dialog dialog;

    private final int PRE_ENCASH = 3;
    private final int ENCASH = 0;
    private final int BIND_ALI = 1;

    private myReceiver myReceiver;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS://成功返回
                    switch (msg.arg1) {
                        case PRE_ENCASH://提现
                            try {
                                final JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                String err_code = jsonObject.getString("err_code");
                                switch (err_code) {
                                    case "1":
                                        //ali请求绑定
                                        String params = jsonObject.getString("params");
                                        nativeZhifubaoLogin(params);
                                        break;
                                    case "2":
                                        //wx请求绑定
                                        WaitingDialog.showWaitingDialog(EnCash.this);
                                        MyWxApi.Login();
                                        break;
                                    case "3":
                                        //账户不满10元不能提现,抱歉
                                        break;
                                    case "0":
                                        //申请提现成功
                                        String username = jsonObject.getString("username");
                                        String headimgurl = jsonObject.getString("headimgurl");
                                        encashDialog = new EncashDialog(EnCash.this);
                                        encashDialog.setCancelable(true);
                                        encashDialog.show();
                                        encashDialog.setInformation(username, headimgurl);
                                        encashDialog.setConfirmListener(new EncashDialog.ConfirmListener() {
                                            @Override
                                            public void confirmListener() {
                                                encash();
                                            }
                                        });
                                        encashDialog.setReBindListener(new EncashDialog.ReBindListener() {
                                            @Override
                                            public void reBindListener() {
                                                WaitingDialog.showWaitingDialog(EnCash.this);
                                                if ("wx".equals(type)) {
                                                    MyWxApi.Login();
                                                } else {
                                                    try {
                                                        if (jsonObject.getString("params") != null) {
                                                            nativeZhifubaoLogin(jsonObject.getString("params"));
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            }
                                        });
                                        break;
                                    default:
                                        break;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            break;
                        case BIND_ALI://绑定阿里
                            WaitingDialog.closeWaitingDialog();
                            break;
                        case ENCASH:
                            //提现成功
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                if ("0".equals(jsonObject.getString("err_code"))) {
                                    money = "0";
                                    encash_price.setText(money);
                                    encash_money.setText(money);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case SDK_PAY_FLAG:
                    Map<String, String> result = (Map<String, String>) msg.obj;
                    String resultStatus = result.get("result");
                    if (resultStatus != null) {
                        bindAli(resultStatus);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        money = getIntent().getStringExtra("money");
        initView();
        registerReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WaitingDialog.closeWaitingDialog();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        money = intent.getStringExtra("money");
        initView();
        registerReceiver();
    }

    private void initView() {
        common_back.setOnClickListener(this);
        encash_history.setOnClickListener(this);
        encash_weixin_layout.setOnClickListener(this);
        encash_zhifubao_layout.setOnClickListener(this);
        encash_commit.setOnClickListener(this);
        if (!TextUtils.isEmpty(money)) {
            encash_price.setText(money);
            encash_money.setText(money);
        }
        type = "wx";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_back:
                this.finish();
                break;
            case R.id.encash_history:
                Intent intent = new Intent(this, EnCashHistory.class);
                startActivity(intent);
                break;
            case R.id.encash_weixin_layout:
                encash_weixin.setImageResource(R.mipmap.college_evaluate_checked_ima);
                encash_zhifubao.setImageResource(R.mipmap.college_evaluate_check_ima);
                type = "wx";
                break;
            case R.id.encash_zhifubao_layout:
                encash_weixin.setImageResource(R.mipmap.college_evaluate_check_ima);
                encash_zhifubao.setImageResource(R.mipmap.college_evaluate_checked_ima);
                type = "ali";
                break;
            case R.id.encash_commit:
                    preEncash();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myReceiver!=null) {
            this.unregisterReceiver(myReceiver);
        }
    }

    private void registerReceiver() {
        myReceiver = new myReceiver();
        IntentFilter intentFilter = new IntentFilter(Constant.WEIXIN_ACITION_HASBIND);
        this.registerReceiver(myReceiver, intentFilter);
    }


    //提现申请
    private void preEncash() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("type", type);
        new InterNetController(this, Constant.PREWITHDRAW, handler, hashMap, PRE_ENCASH);
    }

    //提现
    private void encash() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("type", type);
        new InterNetController(this, Constant.COMPANYPAYMENT, handler, hashMap, ENCASH);
    }

    //阿里提现
    private void nativeZhifubaoLogin(final String parmas) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                AuthTask alipay = new AuthTask(EnCash.this);
                Map<String, String> result = alipay.authV2(parmas, false);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //绑定支付宝，微信已经在登录就绑定完了
    private void bindAli(String params) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("params", params);
        hashMap.put("type", "ali");
        new InterNetController(this, Constant.BIND, handler, hashMap, BIND_ALI);
    }

    //广播
    class myReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            WaitingDialog.closeWaitingDialog();
        }
    }

}
